package tzjz.example.util;

import cn.hutool.crypto.symmetric.SM4;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * @author fuhb
 * @date 2023/6/13
 * 网格一期SM4加密算法
 */
public class FPSm4Util {
    static{
        Security.addProvider(new BouncyCastleProvider());
    }

    protected static final byte[] KEY = "key@fancybull.cn".getBytes(StandardCharsets.UTF_8);

    private final static SM4 sm4 = new SM4(KEY);

    private final static Pattern PATTERN_BASE64 = Pattern.compile("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$");


    protected static String encrypt(String value) {
        return sm4.encryptBase64(value);
    }

    protected static String decrypt(String value) {
        return sm4.decryptStr(value);
    }

    public static String encryptXml(String value) {
        if (StringUtils.isBlank(value)) {
            return value;
        } else if (StringUtils.isNotBlank(tag())) {
            Matcher matcher = Pattern.compile(String.format("^[<%s>]+(?<value>(.*?))[</%s>]+$", tag(), tag())).matcher(value);
            return matcher.matches() ? String.format("<%s>%s</%s>", tag(), matcher.group("value"), tag()) : String.format("<%s>%s</%s>", tag(), encrypt(value), tag());
        } else if (!PATTERN_BASE64.matcher(value).matches()) {
            return encrypt(value);
        } else {
            try {
                decrypt(value);
                return value;
            } catch (Exception var3) {
                return encrypt(value);
            }
        }
    }

    public static String decryptXml(String value) {
        if (StringUtils.isBlank(value)) {
            return value;
        } else if (StringUtils.isNotBlank(tag())) {
            try {
                Matcher matcher = Pattern.compile(String.format("^[<%s>]+(?<value>(.*?))[</%s>]+$", tag(), tag())).matcher(value);
                return matcher.matches() ? decryptXml(decrypt(matcher.group("value"))) : decrypt(value);
            } catch (Exception var3) {
                return value;
            }
        } else {
            try {
                String decryptStr = decrypt(StringUtils.trim(value));
                return decryptXml(decryptStr);
            } catch (Exception var4) {
                return value;
            }
        }
    }

    protected static String tag() {
        return "¥";
    }

    public static final String tagStart(){
        return "<¥>";
    }
    public static final String tagEnd(){
        return "</¥>";
    }

    public static void main(String[] args) {
        System.out.println(decryptXml("<¥>LmRdJrwoRDgm19IN2vt81UCaBw8U39Gh8y2bxuVPyBg=</¥>"));
        //<¥>fS1FhxJcnNydUXxk9vHBjg==</¥>
        //<¥>Tm56DIRhHlZw9oJmZw52ng==</¥>
        System.out.println(encryptXml("1,1"));
    }
}
